import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  Select,
  message
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { getChannelsApi, createArticlesApi, uploadArticlesApi } from '@/apis/publicke'
import { getArticlesApi } from '@/apis/atircal'
import { Link, useSearchParams } from 'react-router-dom'
import './index.scss'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { useEffect, useState } from 'react'
import { useChannels } from '@/hooks/useChannels'


const { Option } = Select

const Publish = () => {
  const [searchParams] = useSearchParams()
  const id = searchParams.get('id')
  const { channelsList } = useChannels()

  const [form] = Form.useForm();
  useEffect(()=> {
    const getlist = async() => {

        const res = await getArticlesApi(id)
        const { cover } = res.data
        form.setFieldsValue(
          { ...res.data, type: cover.type  }
        )
        setImageStage(cover.type)
        setFileList(cover.images.map(item => ({
          url: item
        })))
      
    }
    if(id){
      getlist()
    }

  },[id, form])

  const onFinish = (value) => {
    const { channel_id, content, title } = value
    if(imageStage !== 0 && imageStage !== fileList.length){
       return message.error('封面和图片不匹配')
    }
    const data = {
      title,
      content,
      channel_id,
      cover: {
        type: imageStage,
        images: fileList.map(item => {
          if(item.response){
            return item.response.data.url
          }else { 
            return item.url
          }
        })
      }
    }
    if(id) {
      uploadArticlesApi({ id: id, ...data })
    }else {
      createArticlesApi(data)
    }

  }

  const [ fileList, setFileList ] = useState([])
  const beforeUpload = (file) => {
    console.log(file);
    const isState = file.type === 'image/jpeg' || file.type === 'image/png'
    if(!isState ){
      return message.error('请上床jpeg, jpg,png后缀的图片');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
     return message.error('图片的大小在2MB以内');
    }
    return isState && isLt2M;
  }
  const onChange = (value) => {
    setFileList(value.fileList)
  }

  const [ imageStage, setImageStage ] = useState(0)
  const groupChange = (e) => {
    setImageStage(e.target.value)
  }
  return (
    <div className="publish">
      <Card
        title={
          <Breadcrumb items={[
            { title: <Link to={'/'}>首页</Link> },
            { title: id ?  '发布文章' : '编辑文章'},
          ]}
          />
        }
      >
        <Form
          form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 0 }} //单选框，默认值
          onFinish={onFinish}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}
          >
            <Select placeholder="请选择文章频道" style={{ width: 400 }}>
              { channelsList.map(item => <Option key={item.id} value={item.id}>{ item.name }</Option>) }
            </Select>
          </Form.Item>

          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={groupChange}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>

            { imageStage > 0  &&   <Upload
              maxCount={imageStage}
              listType="picture-card"
              showUploadList
              fileList={fileList}
              onChange={onChange}
              beforeUpload={beforeUpload}
              action={'http://geek.itheima.net/v1_0/upload'}  //这个上传文件的地址，
              name='image' //上传文件的参数名字
            >
              <div style={{ marginTop: 8 }}>
                <PlusOutlined />
              </div>
            </Upload>}
         
        </Form.Item>

          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
          <ReactQuill
            className="publish-quill"
            theme="snow"
            placeholder="请输入文章内容"
        />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                发布文章
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Publish
